package com.linhh.mall.center.web.controller;

import com.csvreader.CsvWriter;
import com.github.pagehelper.PageInfo;
import com.linhh.mall.center.api.CategoryInfoService;
import com.linhh.mall.center.common.pojo.CategoryInfo;
import com.linhh.mall.center.common.util.FileUtil;
import com.linhh.mall.center.common.util.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类管理控制层
 * @Author linhh
 * @Date 2022 10 27 00 37
 **/
@Api(tags = "商城：商品分类管理")
@RestController
@RequestMapping("api")
public class CategoryInfoController {
    @Reference
    private CategoryInfoService categoryInfoService;

    @PutMapping("/updateCategory")
    public int updateCategoryInfo(CategoryInfo categoryInfo){
        return categoryInfoService.updateCategory(categoryInfo);
    }

    /**
     * 查询所有商品分类
     * @return
     */
    @ApiOperation(value = "获取全部商品分类")
    @GetMapping(value = "/queryCategory")
    public HttpResult queryAllCategory(Integer page, Integer size){
        List<CategoryInfo> categories = categoryInfoService.selectAllCateGory();
        PageInfo<CategoryInfo> pageInfo = new PageInfo<>(categories);
        return HttpResult.success(pageInfo);
    }

    /**
     * 查询二级商品分类
     * @return
     */
    @ApiOperation(value = "获取前两级商品分类")
    @GetMapping(value = "/queryCategoryLevel2")
    public HttpResult queryCategoryLevel2(){
        List<CategoryInfo> categories = categoryInfoService.selectCategoryLevel2();
        return HttpResult.success(categories);
    }



    @GetMapping(value = "/createCategoryCsv")
    public HttpResult createCsv(){
        String filePath = "D:/mall_center/test2.csv";
        int result = 0;

        CsvWriter csvWriter = null;

        try {
            csvWriter = new CsvWriter(filePath,',', Charset.forName("utf-8"));
            String[] headers = {"id","分类名称","父ID","层级","顺序","状态"};
            csvWriter.writeRecord(headers);
            List<CategoryInfo> categoryInfos = categoryInfoService.selectAllCateGory();
            for(CategoryInfo categoryInfo:categoryInfos){
                List<String> contentlist = new ArrayList<>();
                contentlist.add(String.valueOf(categoryInfo.getId()));
                contentlist.add(categoryInfo.getCategoryName());
                contentlist.add(String.valueOf(categoryInfo.getParentId()));
                contentlist.add(String.valueOf(categoryInfo.getLevel()));
                contentlist.add(String.valueOf(categoryInfo.getSort()));
                contentlist.add(String.valueOf(categoryInfo.getStatus()));

                String[] array = contentlist.toArray(new String[contentlist.size()]);
                csvWriter.writeRecord(array);
                result++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            csvWriter.close();
        }

        return HttpResult.success(result);

    }

    /**
     * 下载CSV文件
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/downloadCategoryCsv")
    public void downloadAllCategory(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = "test2.csv";
        String realpath = "D:/file/mall_center";
        File file = new File(realpath,fileName);

        if(file.exists()){
            FileInputStream fis = null;
            BufferedInputStream bis = null;

            try {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

                byte[] buffer = new byte[1024];
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();

                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer,0,i);
                    i = bis.read(buffer);
                }

                System.out.println("download the file success");

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(bis!=null){
                    bis.close();
                }

                if(fis!=null){
                    fis.close();
                }
            }
        }
    }

    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @PostMapping("/uploadFile")
    public HttpResult uploadFile(@RequestParam("file") MultipartFile multipartFile){
        String result = null;
        String directory = "D:/file/mall_center";

        try {
            File file = FileUtil.toFile(multipartFile,directory);
            boolean b = file.createNewFile();
            System.out.println(file.getName());
            result = file.getName();

        } catch (IOException e) {
            e.printStackTrace();
            result = "服务异常";
        }
        return HttpResult.success(result);
    }
}
